/**
 * @author        Nicolas Bottarini <nicolasbottarini@gmail.com>, 404 <http://www.proyecto404.com>
 * @version       $Rev: 3 $
 * @lastrevision  $Date: 2011-09-12 16:45:37 +0000 (Mon, 12 Sep 2011) $	 
 */
package com.proyecto404.core {
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import mx.olap.aggregators.MaxAggregator;
	
	import org.osflash.signals.ISignal;
	import org.osflash.signals.Signal;

	/**  
	 * Clase Delay sacada de http://bit.ly/bDrpwC 
	 */  
	public class Timer extends BaseObject {
		private var _interval:Number;  
		private var _times:Number;        
		private var _timer:flash.utils.Timer;  
		private var _tick:Signal;
		private var _startTime:Number;
		private var _paused:Boolean;
		
		function Timer(interval:Number, times:Number = 0) {  
			_interval = interval;  
			_times = times; 
			_tick = new Signal(TimerEventArgs);
			_paused = false;
			init();
		}  
		
		private function init():void {  
			_timer = new flash.utils.Timer(_interval, _times);  
			_timer.addEventListener(TimerEvent.TIMER, function():void {
				_startTime = (new Date()).time;
				_timer.delay = _interval;
				_tick.dispatch(new TimerEventArgs(_timer.currentCount));
			});  
		}  
		
		public function get tick():ISignal {
			return _tick;
		}  
		
		public function isRunning():Boolean {
			return _timer.running;
		}
		
		public function start():void {
			if(_timer.currentCount < _timer.repeatCount || _timer.repeatCount == 0) {  
				_timer.delay = _interval;
				_paused = false;  
				_startTime = (new Date()).time;  
				_timer.start();  
			}  
		}
		
		public function stop():void {  
			_timer.stop();
		}  

		public function pause():void {
			if (_timer.running) {
				_paused = true;
				_timer.stop();
				_timer.delay = Math.max(0, _timer.delay - ((new Date()).time - _startTime));
			}
		}  

		public function get paused():Boolean {
			return _paused;
		}  
		
		public function resume() : void {
			if(_timer.currentCount < _timer.repeatCount || _timer.repeatCount == 0){
				_paused = false;
				_startTime = (new Date()).time;
				_timer.start();
			}
		}
	}  
}